#!/bin/bash

# 英语词汇量估算系统自动化部署脚本
# 使用方法: ./deploy.sh [域名]

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
PROJECT_NAME="englishvet"
PROJECT_DIR="/var/www/$PROJECT_NAME"
DOMAIN=${1:-"localhost"}
USER=$(whoami)

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [ "$EUID" -eq 0 ]; then
        log_error "请不要使用root用户运行此脚本"
        exit 1
    fi
}

# 检查系统要求
check_system() {
    log_step "检查系统要求..."
    
    # 检查操作系统
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        log_info "操作系统: $NAME $VERSION"
    else
        log_warn "无法确定操作系统版本"
    fi
    
    # 检查Python版本
    if command -v python3 &> /dev/null; then
        PYTHON_VERSION=$(python3 --version | cut -d' ' -f2)
        log_info "Python版本: $PYTHON_VERSION"
    else
        log_error "Python3未安装"
        exit 1
    fi
    
    # 检查pip
    if command -v pip3 &> /dev/null; then
        log_info "pip3已安装"
    else
        log_error "pip3未安装"
        exit 1
    fi
}

# 安装系统依赖
install_dependencies() {
    log_step "安装系统依赖..."
    
    if command -v apt &> /dev/null; then
        # Ubuntu/Debian
        sudo apt update
        sudo apt install -y python3-venv python3-pip nginx ufw curl
    elif command -v yum &> /dev/null; then
        # CentOS/RHEL
        sudo yum update -y
        sudo yum install -y python3 python3-pip nginx ufw curl
    else
        log_error "不支持的包管理器"
        exit 1
    fi
    
    log_info "系统依赖安装完成"
}

# 创建项目目录
create_project_dir() {
    log_step "创建项目目录..."
    
    sudo mkdir -p $PROJECT_DIR
    sudo chown $USER:$USER $PROJECT_DIR
    sudo chmod 755 $PROJECT_DIR
    
    log_info "项目目录创建完成: $PROJECT_DIR"
}

# 复制项目文件
copy_project_files() {
    log_step "复制项目文件..."
    
    # 获取脚本所在目录
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    
    # 复制所有项目文件
    cp -r "$SCRIPT_DIR"/* "$PROJECT_DIR/"
    
    # 设置权限
    sudo chown -R $USER:$USER "$PROJECT_DIR"
    sudo chmod -R 755 "$PROJECT_DIR"
    
    log_info "项目文件复制完成"
}

# 创建虚拟环境
setup_virtual_env() {
    log_step "设置Python虚拟环境..."
    
    cd $PROJECT_DIR
    
    # 创建虚拟环境
    python3 -m venv venv
    source venv/bin/activate
    
    # 升级pip
    pip install --upgrade pip
    
    # 安装依赖
    if [ -f requirements.txt ]; then
        pip install -r requirements.txt
        log_info "项目依赖安装完成"
    else
        log_warn "requirements.txt文件不存在"
    fi
    
    # 安装生产环境依赖
    pip install gunicorn gevent
    
    log_info "虚拟环境设置完成"
}

# 配置应用
configure_app() {
    log_step "配置应用..."
    
    cd $PROJECT_DIR
    
    # 生成随机密钥
    SECRET_KEY=$(python3 -c "import secrets; print(secrets.token_hex(32))")
    
    # 创建配置文件
    cat > config_production.py << EOF
# 生产环境配置
import os

class ProductionConfig:
    SECRET_KEY = '$SECRET_KEY'
    SQLALCHEMY_DATABASE_URI = 'sqlite:///vocabulary.db'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    MAX_CONTENT_LENGTH = 10 * 1024 * 1024  # 10MB
    
    # 日志配置
    LOG_LEVEL = 'INFO'
    LOG_FILE = '/var/log/englishvet/app.log'
    
    # 安全配置
    SESSION_COOKIE_SECURE = True
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SAMESITE = 'Lax'
EOF
    
    log_info "应用配置完成"
}

# 初始化数据库
init_database() {
    log_step "初始化数据库..."
    
    cd $PROJECT_DIR
    source venv/bin/activate
    
    python3 -c "
from app import app, db
with app.app_context():
    db.create_all()
    print('数据库初始化完成')
"
    
    log_info "数据库初始化完成"
}

# 配置Nginx
configure_nginx() {
    log_step "配置Nginx..."
    
    # 创建Nginx配置
    sudo tee /etc/nginx/sites-available/$PROJECT_NAME > /dev/null << EOF
server {
    listen 80;
    server_name $DOMAIN;

    # 安全头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;

    # 文件上传大小限制
    client_max_body_size 10M;

    # 静态文件缓存
    location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)\$ {
        alias $PROJECT_DIR/static;
        expires 1y;
        add_header Cache-Control "public, immutable";
        access_log off;
    }

    # 主应用代理
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        
        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    # 日志配置
    access_log /var/log/nginx/${PROJECT_NAME}_access.log;
    error_log /var/log/nginx/${PROJECT_NAME}_error.log;
}
EOF
    
    # 启用站点
    sudo ln -sf /etc/nginx/sites-available/$PROJECT_NAME /etc/nginx/sites-enabled/
    
    # 测试配置
    sudo nginx -t
    
    # 重载Nginx
    sudo systemctl reload nginx
    
    log_info "Nginx配置完成"
}

# 配置systemd服务
configure_systemd() {
    log_step "配置systemd服务..."
    
    sudo tee /etc/systemd/system/$PROJECT_NAME.service > /dev/null << EOF
[Unit]
Description=English Vocabulary Estimator
After=network.target

[Service]
Type=notify
User=www-data
Group=www-data
WorkingDirectory=$PROJECT_DIR
Environment="PATH=$PROJECT_DIR/venv/bin"
Environment="PYTHONPATH=$PROJECT_DIR"
ExecStart=$PROJECT_DIR/venv/bin/gunicorn -c gunicorn.conf.py app:app
ExecReload=/bin/kill -s HUP \$MAINPID
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=$PROJECT_NAME

# 安全设置
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$PROJECT_DIR /var/log/englishvet /var/backups/englishvet

[Install]
WantedBy=multi-user.target
EOF
    
    # 重新加载systemd
    sudo systemctl daemon-reload
    
    log_info "systemd服务配置完成"
}

# 创建日志目录
create_log_dirs() {
    log_step "创建日志目录..."
    
    sudo mkdir -p /var/log/englishvet
    sudo mkdir -p /var/backups/englishvet
    sudo chown www-data:www-data /var/log/englishvet
    sudo chown www-data:www-data /var/backups/englishvet
    
    log_info "日志目录创建完成"
}

# 配置防火墙
configure_firewall() {
    log_step "配置防火墙..."
    
    sudo ufw allow 22/tcp
    sudo ufw allow 80/tcp
    sudo ufw allow 443/tcp
    sudo ufw --force enable
    
    log_info "防火墙配置完成"
}

# 启动服务
start_services() {
    log_step "启动服务..."
    
    # 启动应用服务
    sudo systemctl start $PROJECT_NAME
    sudo systemctl enable $PROJECT_NAME
    
    # 确保Nginx运行
    sudo systemctl start nginx
    sudo systemctl enable nginx
    
    # 检查服务状态
    if sudo systemctl is-active --quiet $PROJECT_NAME; then
        log_info "应用服务启动成功"
    else
        log_error "应用服务启动失败"
        sudo systemctl status $PROJECT_NAME
        exit 1
    fi
    
    if sudo systemctl is-active --quiet nginx; then
        log_info "Nginx服务启动成功"
    else
        log_error "Nginx服务启动失败"
        sudo systemctl status nginx
        exit 1
    fi
}

# 设置备份
setup_backup() {
    log_step "设置备份..."
    
    # 设置备份脚本权限
    sudo chmod +x $PROJECT_DIR/backup.sh
    
    # 添加到crontab
    (crontab -l 2>/dev/null; echo "0 2 * * * $PROJECT_DIR/backup.sh") | crontab -
    
    log_info "备份设置完成"
}

# 显示部署信息
show_deployment_info() {
    log_step "部署完成！"
    
    echo ""
    echo "=========================================="
    echo "部署信息:"
    echo "=========================================="
    echo "项目名称: $PROJECT_NAME"
    echo "项目目录: $PROJECT_DIR"
    echo "域名: $DOMAIN"
    echo "访问地址: http://$DOMAIN"
    echo ""
    echo "服务状态:"
    echo "- 应用服务: $(sudo systemctl is-active $PROJECT_NAME)"
    echo "- Nginx服务: $(sudo systemctl is-active nginx)"
    echo ""
    echo "常用命令:"
    echo "- 查看应用日志: sudo journalctl -u $PROJECT_NAME -f"
    echo "- 重启应用: sudo systemctl restart $PROJECT_NAME"
    echo "- 查看Nginx日志: sudo tail -f /var/log/nginx/${PROJECT_NAME}_error.log"
    echo "- 手动备份: $PROJECT_DIR/backup.sh"
    echo "=========================================="
}

# 主函数
main() {
    log_info "开始部署英语词汇量估算系统..."
    
    check_root
    check_system
    install_dependencies
    create_project_dir
    copy_project_files
    setup_virtual_env
    configure_app
    init_database
    configure_nginx
    configure_systemd
    create_log_dirs
    configure_firewall
    start_services
    setup_backup
    show_deployment_info
    
    log_info "部署完成！"
}

# 运行主函数
main "$@" 